/*
 * This file is part of Smart Route for S60 3rd Edition terminals
 * 
 * Copyright (C) 2006  Harri Salminen

 * This program free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 *(at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include <barsread.h> 
#include <stringloader.h>
#include <aknlists.h>
#include <eikenv.h>
#include <akniconarray.h>
#include <eikclbd.h>
#include <aknviewappui.h>
#include <eikappui.h>
#include "MainScreen.h"
#include "SmartRoute.rsg"
#include "MainScreenView.h"
#include "SmartRoute.hrh"
#include "MainScreen.hrh"
#include "TripInfo.hrh"
#include "Smartroute_mbm.mbg"
#include "SmartRouteAppUi.h"

_LIT( KSmartroute_mbmFile, "\\resource\\apps\\Smartroute_mbm.mbm" );
CMainScreen::CMainScreen()
	{
	iListBox = NULL;
	}

CMainScreen::~CMainScreen()
	{
	delete iListBox;
	}
				
CMainScreen* CMainScreen::NewL( 
		const TRect& aRect, 
		const CCoeControl* aParent, 
		MEikCommandObserver* aCommandObserver )
	{
	CMainScreen* self = CMainScreen::NewLC( aRect, aParent, aCommandObserver );
	CleanupStack::Pop( self );
	return self;
	}

CMainScreen* CMainScreen::NewLC( 
		const TRect& aRect, 
		const CCoeControl* aParent, 
		MEikCommandObserver* aCommandObserver )
	{
	CMainScreen* self = new (ELeave) CMainScreen();
	CleanupStack::PushL( self );
	self->ConstructL( aRect, aParent, aCommandObserver );
	return self;
	}
			
void CMainScreen::ConstructL( 
		const TRect& aRect, 
		const CCoeControl* aParent, 
		MEikCommandObserver* aCommandObserver )
	{
    if ( !aParent )
        {
    	CreateWindowL();
        }
    else
        {
        SetContainerWindowL( *aParent );
        }
	iFocusControl = NULL;
	iCommandObserver = aCommandObserver;
    InitializeControlsL();
    SetRect( aRect );
	ActivateL();
	}
			
TInt CMainScreen::CountComponentControls() const
	{
	return (int) ELastControl;
	}
				
CCoeControl* CMainScreen::ComponentControl( TInt aIndex ) const
	{
	switch ( aIndex )
		{
	case EListBox:
		return iListBox;
		}
	return NULL;
	}
							
void CMainScreen::SizeChanged()
	{
	CCoeControl::SizeChanged();
	LayoutControls();
	}
				
void CMainScreen::LayoutControls()
	{
	iListBox->SetExtent( TPoint( 0, 0 ), iListBox->MinimumSize() );
	}
			
TKeyResponse CMainScreen::OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType )
	{
	if ( ( aKeyEvent.iCode == EKeyLeftArrow ) || ( aKeyEvent.iCode == EKeyRightArrow ) )
	    {
	    return EKeyWasNotConsumed;
	    }
	if ( aKeyEvent.iCode == EKeyOK)
	    {
        const TInt currItem = iListBox->CurrentItemIndex();
        CSmartRouteAppUi* appUi = static_cast<CSmartRouteAppUi*>(CEikonEnv::Static()->AppUi());
    	TSmartRouteState state = appUi->EngineL().State();
        /**
         * Command depends on state and selected item
         * State == Running -> Pause, Stop
         * State == Paused  -> Resume, Stop
         * State == Stopped -> Start, Show
         */
        switch(state)
        	{
        	case ERouteIdle:
        		switch(currItem)
        			{
        			case 0: 
        				iCommandObserver->ProcessCommandL(ESmartRouteStart);
        				break;
        			case 1: 
        				iCommandObserver->ProcessCommandL(ESmartRouteShow);
        				break;
        			}
        		break;
			case ERouteRecording:
				switch(currItem)
					{
					case 0: 
						iCommandObserver->ProcessCommandL(ESmartRoutePause);
						break;
					case 1:
						iCommandObserver->ProcessCommandL(ESmartRouteStop);
					}
				break;
			case ERoutePaused:
				switch(currItem)
					{
					case 0:
						iCommandObserver->ProcessCommandL(ESmartRouteResume);
						break;
					case 1:
						iCommandObserver->ProcessCommandL(ESmartRouteStop);
						break;
					}
				break;
			}
	    return EKeyWasNotConsumed;
	    }
	    
	if ( iFocusControl &&
			iFocusControl->OfferKeyEventL( aKeyEvent, aType ) == EKeyWasConsumed )
		return EKeyWasConsumed;
	return CCoeControl::OfferKeyEventL( aKeyEvent, aType );
	}
				
void CMainScreen::InitializeControlsL()
	{
	iListBox = new (ELeave) CAknSingleLargeStyleListBox;
	iListBox->SetContainerWindowL( *this );
		{
		TResourceReader reader;
		iEikonEnv->CreateResourceReaderLC( reader, R_MAIN_SCREEN_LIST_BOX );
		iListBox->ConstructFromResourceL( reader );
		CleanupStack::PopAndDestroy();
		}
	iListBox->Model()->SetOwnershipType( ELbmOwnsItemArray );
	SetupListBoxIconsL();
	iListBox->SetFocus( ETrue );
	iFocusControl = iListBox;
	}

void CMainScreen::HandleResourceChange( TInt aType )
	{
	CCoeControl::HandleResourceChange( aType );
	SetRect( iAvkonViewAppUi->View( TUid::Uid( EMainScreenViewId ) )->ClientRect() );
	}
							
void CMainScreen::Draw( const TRect& aRect ) const
	{
	CWindowGc& gc = SystemGc();
	gc.Clear( aRect );
	}
				
void CMainScreen::AddListBoxItemL( CEikTextListBox* aListBox, const TDesC& aString )
	{
	CTextListBoxModel* model = aListBox->Model();
	CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
	itemArray->AppendL( aString );
	aListBox->HandleItemAdditionL();
	}
				
RArray< TInt >* CMainScreen::GetSelectedListBoxItemsLC( CEikTextListBox* aListBox )
	{
	CAknFilteredTextListBoxModel* model = 
		static_cast< CAknFilteredTextListBoxModel *> ( aListBox->Model() );
	if ( model->NumberOfItems() == 0 )
		return NULL;
		
	const CListBoxView::CSelectionIndexArray* selectionIndexes =
		aListBox->SelectionIndexes();
	TInt selectedIndexesCount = selectionIndexes->Count();
	if ( selectedIndexesCount == 0 )
		return NULL;
		
	RArray<TInt>* orderedSelectedIndices = 
		new (ELeave) RArray< TInt >( selectedIndexesCount );
	
	CleanupStack::PushL( orderedSelectedIndices );
	CleanupClosePushL( *orderedSelectedIndices );
	CAknListBoxFilterItems* filter = model->Filter();
	if ( filter != NULL )
		{
		for ( TInt idx = 0; idx < selectedIndexesCount; idx++ )
			{
			TInt filteredItem = ( *selectionIndexes ) [ idx ];
			TInt actualItem = filter->FilteredItemIndex ( filteredItem );
			orderedSelectedIndices->InsertInOrder( actualItem );
			}
		}
	else
		{
		for ( TInt idx = 0; idx < selectedIndexesCount; idx++ )
			orderedSelectedIndices->InsertInOrder( ( *selectionIndexes ) [ idx ] );
		}	
		
	return orderedSelectedIndices;
	}

void CMainScreen::DeleteSelectedListBoxItemsL( CEikTextListBox* aListBox )
	{
	CAknFilteredTextListBoxModel* model = 
		static_cast< CAknFilteredTextListBoxModel *> ( aListBox->Model() );
	if ( model->NumberOfItems() == 0 )
		return;

	RArray< TInt >* orderedSelectedIndices = GetSelectedListBoxItemsLC( aListBox );		
	if ( !orderedSelectedIndices )
		return;
		
	CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
	TInt currentItem = 0;
	
	for ( TInt idx = orderedSelectedIndices->Count(); idx-- > 0; ) 
		{
		currentItem = ( *orderedSelectedIndices )[ idx ];
		itemArray->Delete ( currentItem );
		}

	CleanupStack::PopAndDestroy();
	CleanupStack::PopAndDestroy( orderedSelectedIndices );
	AknListBoxUtils::HandleItemRemovalAndPositionHighlightL(
		aListBox, currentItem, ETrue );
	}

CAknSingleLargeStyleListBox* CMainScreen::ListBox()
	{
	return iListBox;
	}

void CMainScreen::CreateListBoxItemL( TDes& aBuffer, TInt aIconIndex,
		const TDesC& aMainText )
	{
	_LIT ( KStringHeader, "%d\t%S" );

	aBuffer.Format( KStringHeader(), aIconIndex, &aMainText );
	}

void CMainScreen::AddListBoxResourceArrayItemL( TInt aResourceId, TInt aIconIndex )
	{
	CDesCArray* array = iCoeEnv->ReadDesCArrayResourceL( aResourceId );
	CleanupStack::PushL( array );
	TBuf<512> listString; 
	CreateListBoxItemL( listString, aIconIndex, ( *array ) [ 0 ] );
	AddListBoxItemL( iListBox, listString );
	CleanupStack::PopAndDestroy( array );
	}

void CMainScreen::SetupListBoxIconsL()
	{
	CArrayPtr< CGulIcon >* icons = NULL;		
	icons = new (ELeave) CAknIconArray( 1 );
	CleanupStack::PushL( icons );
	icons->AppendL( LoadAndScaleIconL(
			KSmartroute_mbmFile, EMbmSmartroute_mbmList_icon, EMbmSmartroute_mbmList_icon_mask,
			NULL, EAspectRatioPreserved ) );
	CleanupStack::Pop( icons );
	
	if ( icons )
		iListBox->ItemDrawer()->ColumnData()->SetIconArray( icons );
	}

TBool CMainScreen::HandleMarkableListCommandL( TInt aCommand )
	{
	 
	return EFalse;
	}

CGulIcon* CMainScreen::LoadAndScaleIconL( const TDesC& aFileName, TInt aBitmapId, TInt aMaskId, TSize* aSize, TScaleMode aScaleMode )
	{
	CFbsBitmap *bitmap, *mask;
	AknIconUtils::CreateIconL( bitmap, mask, aFileName, aBitmapId, aMaskId );
	
	TSize size;
	if ( !aSize )
		{
		AknIconUtils::PreserveIconData( bitmap );
		AknIconUtils::GetContentDimensions( bitmap, size );
		}
	else
		size = *aSize;
	
	AknIconUtils::SetSize( bitmap, size, aScaleMode );
	AknIconUtils::SetSize( mask, size, aScaleMode );
	
	if ( !aSize )
		AknIconUtils::DestroyIconData( bitmap );
	
	return CGulIcon::NewL( bitmap, mask );
	}

void CMainScreen::ClearListL()
    {
    CTextListBoxModel* model = iListBox->Model();
	CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
	itemArray->Reset();
	iListBox->HandleItemRemovalL();
    }
    
void CMainScreen::SetupRunningL()
    {
    ClearListL();
    AddListBoxResourceArrayItemL( R_MAIN_SCREEN_LISTBOX_ITEM_PAUSE,
			EListBoxSmartroute_mbmList_iconIndex );
   	AddListBoxResourceArrayItemL( R_MAIN_SCREEN_LISTBOX_ITEM_STOP,
			EListBoxSmartroute_mbmList_iconIndex );
    }
    
void CMainScreen::SetupPausedL()
    {
    ClearListL();
    AddListBoxResourceArrayItemL( R_MAIN_SCREEN_LISTBOX_ITEM_RESUME,
			EListBoxSmartroute_mbmList_iconIndex );
    AddListBoxResourceArrayItemL( R_MAIN_SCREEN_LISTBOX_ITEM_STOP,
			EListBoxSmartroute_mbmList_iconIndex );
    }
    
void CMainScreen::SetupStoppedL()
    {
    ClearListL();
    AddListBoxResourceArrayItemL( R_MAIN_SCREEN_LISTBOX_ITEM_START,
			EListBoxSmartroute_mbmList_iconIndex );
	AddListBoxResourceArrayItemL( R_MAIN_SCREEN_LISTBOX_ITEM_SHOW,
			EListBoxSmartroute_mbmList_iconIndex );
    }
 
